package org.msfj.admin.data.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.msfj.admin.data.service.FormFieldService;
import org.msfj.admin.model.FormField;
import org.msfj.admin.vo.FormFieldVo;
import org.msfj.admin.data.service.FormFieldService;
import org.msfj.admin.model.FormField;
import org.msfj.admin.vo.FormFieldVo;
import org.msfj.admin.data.service.FormFieldService;
import org.msfj.admin.model.FormField;
import org.msfj.admin.vo.FormFieldVo;
import org.msfj.common.annotation.Constants;
import org.msfj.common.base.BaseServiceImpl;
import org.msfj.common.enums.Enable;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@CacheConfig(cacheNames = Constants.CACHE_NAMESPACE + "form_field")
public class FormFieldServiceImpl extends BaseServiceImpl<FormField> implements FormFieldService {
    @Override
    public FormFieldVo setOtherProperties(FormField formField) {
        if (formField == null) {
            return null;
        }
        FormFieldVo formFieldVo = new FormFieldVo();
        BeanUtils.copyProperties(formField, formFieldVo);
        return formFieldVo;
    }

    @Override
    public List<FormFieldVo> setOtherProperties(List<FormField> formField) {
        if (formField == null) {
            return Collections.emptyList();
        }

        List<FormFieldVo> result = new ArrayList<>();
        for (FormField field : formField) {
            if (field != null) {
                result.add(this.setOtherProperties(field));
            }
        }
        return result;
    }

    @Override
    public PageInfo<FormFieldVo> getByFormField(FormFieldVo formFieldVo, Integer page, Integer rows) {

        Example example = new Example(FormField.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("enable", Enable.ENABLE.getCode());
        if (StrUtil.isNotBlank(formFieldVo.getLabel())) {
            criteria.andLike("label", "%" + formFieldVo.getLabel() + "%");
        }
        example.setOrderByClause("label_ asc");
        PageHelper.startPage(page, rows);
        List<FormField> formFieldList = super.getByExample(example);
        PageInfo formFieldPageInfo = new PageInfo(formFieldList);
        formFieldPageInfo.setList(setOtherProperties(formFieldList));
        return formFieldPageInfo;
    }


    @Override
    public List<FormFieldVo> getAllFormField(FormFieldVo formFieldVo) {
        Example ex = new Example(FormField.class);
        List<FormField> list = super.getByExample(ex);
        if (list != null) {
            return this.setOtherProperties(list);
        }
        return Collections.emptyList();
    }
}
